import * as gameTypes from '../types/gameTypes' 

const initialState: gameTypes.GameState = {}

export default (state = initialState, action: gameTypes.GameAtionTypes) => {
  switch (action.type) {
    case gameTypes.GAME_START:
      action.initGameData.inputPositions = positionsForInputItem(action.initGameData)
      return action.initGameData
    case gameTypes.GAME_INPUT_STEP:
      let newSelectInputIdxs = state.selectInputIdxs.slice()
      let newCurrentInputIdx = state.currentInputIdx
      if (indexForSelectedInputItem(action.inputIndex, state) >= 0) {
        // 已经选择，回退
        newSelectInputIdxs.splice(newSelectInputIdxs.length - 1, 1)
        newCurrentInputIdx -= 1
      } else {    // 加入地图
        newSelectInputIdxs[newCurrentInputIdx] = action.inputIndex
        newCurrentInputIdx += 1
      }
      let newState = {
        ...state,
        selectInputIdxs: newSelectInputIdxs,
        currentInputIdx: newCurrentInputIdx,
        playing: true
      }
      newState.inputPositions = positionsForInputItem(newState)
      return newState
    case gameTypes.GAME_FINISH_ANSWER:
      return {...state, finished: true}
    case gameTypes.GAME_RESTART:
      let restartState = {
        ...state,
        finished: false,
        selectInputIdxs: [],
        currentInputIdx: 0
      }
      restartState.inputPositions = positionsForInputItem(restartState)
      return restartState
    default:
      return state;
  }

}

// Utility
const indexForSelectedInputItem = (inputItemIdx: number, state: gameTypes.GameState) => {
  for (var i = 0, len = state.hurdles.length; i < len; i++) {
    if (state.selectInputIdxs[i] == inputItemIdx) {
      // 被选择在地图中，返回空格的下标
      return i;
    }
  }
  return -1;  // 还未被选择
}
const positionsForInputItem = (state: gameTypes.GameState) => {
  var positions = [];
  // 对于每一个输入的元素，判断是否已经被加入地图中
  state.inputs.forEach((obj: string, idx: number) => {  
    const selectedIdx = indexForSelectedInputItem(idx, state)
    if (selectedIdx >= 0) {  // 被选择在地图中，计算在地图上的位置
      positions.push({
          x: state.hurdles[selectedIdx].x * state.cellWidth,
          y: -state.hurdles[selectedIdx].y * state.cellWidth
      });
    } else {  // 计算在底部inputbar上的位置
      positions.push({
        x: state.inputStartVec2.x + (state.cellWidth + state.inputSpacing) * idx,
        y: state.inputStartVec2.y
      });
    }
  });
  return positions
}